<template>
  <div style="position: relative; min-height: 100vh;">
    <div v-if="loading" class="loading-mask">
      <div class="spinner"></div>
      <div class="loading-text">加载中...</div>
    </div>
    <div v-if="error" style="padding:8px;color:#ee0a24;">{{ error }}</div>
    <div ref="sandboxHost" style="height:100vh;"></div>
  </div>
</template>

<script>
import axios from 'axios'
import { createStringAppSandbox } from '../runtime/sandbox'

export default {
  name: 'Mobile',
  data() {
    return { error: '', loading: false }
  },
  mounted() {
    this.loadApp()
  },
  watch: {
    '$route.query': {
      immediate: false,
      handler() {
        this.loadApp()
      }
    }
  },
  computed: {
    appKey() {
      return this.$route.query.app || 'form'
    }
  },
  methods: {
    async loadApp() {
      this.error = ''
      this.loading = true
      const host = this.$refs.sandboxHost
      if (!host) return
      host.innerHTML = ''
      try {
        const appKey = this.appKey
        const url = import.meta.env.VITE_REGISTRY_URL || 'http://localhost:7070/app-string'
        const { data } = await axios.get(url, { params: { app: appKey } })
        const code = typeof data === 'string' ? data : (data && data.code) || ''
        if (!code) throw new Error('注册中心未返回代码')
        const api = {
          Vue: this.$root.constructor,
          mount: host,
          currentApp: appKey
        }
        await createStringAppSandbox(code, api)
      } catch (e) {
        this.error = e && e.message ? e.message : String(e)
        this.$toast && this.$toast.fail(this.error)
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped>
.loading-mask { position: absolute; inset: 0; background: rgba(255,255,255,0.96); display: flex; flex-direction: column; align-items: center; justify-content: center; z-index: 10; }
.loading-text { margin-top: 8px; color: #323233; font-size: 14px; }
.spinner { width: 28px; height: 28px; border: 3px solid #f2f3f5; border-top-color: #1989fa; border-radius: 50%; animation: spin 0.8s linear infinite; }
@keyframes spin { to { transform: rotate(360deg); } }
</style>


